<?php

namespace Biz\service\Store;

use Biz\cache\store\StoreMsg;
use Biz\model\store\StoreBasic;
use Biz\model\store\StoreOperator;
use Biz\model\store\StoreUserConsult as mUserConsult;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\service\Member;
use Doraemon\tools\Log;
use Doraemon\tools\Sms;
use Hhz\AdministrativeRegion\Region;

class StoreUserConsult
{

    const BIND_STATUS_DEFAULT = 0;
    const BIND_STATUS_OK = 1;

    const START_MSG_TIME = "09:00";
    const END_MSG_TIME = "22:00";
    use _Async;

    /**
     * @param $uid
     * @param int $store_id
     * @param string $phone
     * @param string $area
     * @param $city_id
     * @param string $act_from
     * @param int $wiki_id
     * @param int $area_code
     * @param string $area_name
     * @return array
     * @throws \Exception
     */
    public static function AddConsultInfo(
        $uid,
        $store_id = 0,
        $phone = '',
        $area = '',
        $city_id,
        $act_from = 'StoreHomePage',
        $wiki_id = 0,
        $area_code = 0,
        $area_name = ''
    )
    {
        $act_from = mUserConsult::ACT_SOURCE_MAP[$act_from] ?: 0;
        $consult_info = mUserConsult::getByWhere([
            'store_id' => $store_id,
            'uid' => $uid,
            'phone' => $phone,
            'ORDER' => ['edittime' => 'DESC']
        ]);
        $data = [
            'uid' => $uid,
            'store_id' => $store_id,
            'phone' => $phone,
            'city' => $area,
            'city_id' => $city_id,
            'source' => $act_from,
            'area_code' => $area_code,
            'area_name' => $area_name,
        ];
        if ($wiki_id) {
            $data['wiki_id'] = $wiki_id;
        }
        if ($consult_info) {
            if ($consult_info['bind_status'] == self::BIND_STATUS_OK) {
                if ($phone == $consult_info['phone'] && time() < strtotime($consult_info['virtual_expire_time'])) {
                    $rs = mUserConsult::updateData($data, ['id' => $consult_info['id']]);
                } else {
                    $rs = mUserConsult::add($data);
                }
            } else {
                $rs = mUserConsult::updateData($data, ['id' => $consult_info['id']]);
            }
        } else {
            $rs = mUserConsult::add($data);
            //发送短信提醒
            self::sendMsg($uid, $store_id);
        }
        return $rs;
    }


    /**获取咨询信息
     * @param int $store_id
     * @param int $uid
     * @return array
     */
    public static function getConsultInfo($storeId, $uid)
    {
        $result = [];
        $consult_info = mUserConsult::getByWhere([
            'store_id' => $storeId,
            'uid' => $uid,
            'ORDER' => ['edittime' => 'DESC']
        ]);
        if ($consult_info && is_array($consult_info)) {
            $result['area'] = $consult_info['city'];
            $result['phone'] = $consult_info['phone'];
            $result['city_id'] = $consult_info['city_id'];
            $result['area_code'] = $consult_info['area_code'];
            $result['area_name'] = $consult_info['area_name'];
        }
        return $result;
    }

    /**
     * @desc 获取最后一次留资信息
     * @param $uid
     * @param $store_id
     * @return mixed|null
     */
    public static function getUserLastConsultInfo($uid, $store_id)
    {
        $consult_info = mUserConsult::getByWhere([
            'uid' => $uid,
            'store_id' => $store_id,
            'ORDER' => ['id' => 'DESC']
        ]);
        $result = [];
        if ($consult_info && is_array($consult_info)) {
            $result = $consult_info;
        }
        return $result;
    }


    /**获取留资对应的用户虚拟号
     * @param $consult_id
     * @return array|false
     * @throws \Exception
     */
    public static function getConsultVirtualPhone($consult_id)
    {
        $consult_info = mUserConsult::getByWhere([
            'id' => $consult_id,
        ]);
        //获取门店官方当前回拨电话
        $official_phone = StoreOfficialPhone::GetOfficialPhone($consult_info['store_id']);
        if (empty($official_phone)) {
            throw  new \Exception('请先设置官方回拨号码');
        }
        //绑定虚拟号
        $result = VirtualPhone::createVirtualPhone($official_phone, $consult_info['phone'], $consult_info['store_id'],
            $consult_info['uid'], VirtualPhone::POOL_KEY, VirtualPhone::DIRECTION_OXU);
        if (!empty($result)) {
            $update_result = mUserConsult::updateData(
                [
                    'official_phone' => $official_phone,
                    'virtual_phone' => $result['virtual_phone'],
                    'bind_status' => self::BIND_STATUS_OK,
                    'virtual_expire_time' => $result['virtual_expire_time'],
                ]
                ,
                [
                    'id' => $consult_id
                ]
            );
            if ($update_result) {
                return [
                    'official_phone' => $official_phone,
                    'virtual_phone' => $result['virtual_phone'],
                    'virtual_expire_time' => $result['virtual_expire_time']
                ];
            }
        }
        return false;
    }

    /**发送短信
     * @param int $uid
     * @param int $store_id
     * */
    public static function sendMsg($uid, $store_id)
    {
        $send_time = time();
        $log_params = [
            'time' => date("Y-m-d H:i:s", $send_time),
            'uid' => $uid,
            'store_id' => $store_id
        ];
        if (empty($uid) || empty($store_id)) {
            log::info('参数缺失', ['params' => $log_params]);
            return;
        }
        //只可以 9：00-22：00点发送消息
        if ($send_time < strtotime(self::START_MSG_TIME) || $send_time > strtotime(self::END_MSG_TIME)) {
            log::info('超过发送时间段', ['params' => $log_params]);
            return;
        }
        $day = date("y-m-d", $send_time);
        //今日是否已发送短信
        $is_send = StoreMsg::getByKey($day, $uid, $store_id);
        if ($is_send) {
            log::info('今日已发送过', ['params' => $log_params]);
            return;
        }
        //投送发送队列
        self::_async($uid, $store_id);
    }

    public static function _async_sendMsg($uid, $store_id, $is_record = true)
    {
        //信息是否存在
        $store_info = StoreBasic::getStoreInfoById($store_id);
        if ($store_info['account_id']) {
            $operaterInfo = StoreOperator::getInfoByAid($store_info['account_id']);
        }
        $userInfo = Member::getUserInfoByUid($uid);

        if (empty($operaterInfo['phone']) || empty($userInfo['nick'])) {
            Log::info("信息缺失", [
                'params' => [
                    'uid' => $uid,
                    'phone' => $operaterInfo['phone'],
                    'nick' => $userInfo['nick'],
                    'store_id' => $store_id
                ]
            ]);
            return;
        }
        //准备发送
        $result = Sms::sendSms(
            $operaterInfo['phone'],
            ['name' => $userInfo['nick']],
            [
                'CnTelecom' => Sms::CHINA_TELECOM_CONFIG['temp_remind_store'],
                'CnUnicom' => Sms::CHINA_UNICOM_CONFIG['temp_remind_store'],
                'aliyun' => Sms::TYPE_REMIND_STORE
            ],
            '86'
        );

        if ($result) {
            if ($is_record) {
                //记录今日已发送
                $day = date("y-m-d", time());
                StoreMsg::addByKey($day, $uid, $store_id);
            }
        } else {
            log::info("发短信失败", [
                'params' => [
                    'time' => date("Y-m-d H:i:s", time()),
                    'uid' => $uid,
                    'store_id' => $store_id
                ]
            ]);
        }


    }
}